<template>
    <div class="file-upload-view">
        <div class="page-header">
            <h1 class="page-title">文件上传管理</h1>
            <p class="page-desc">支持多种文件类型的上传、预览和管理功能</p>
        </div>

        <div class="upload-sections">
            <!-- 基础上传 -->
            <div class="upload-section">
                <h2 class="section-title">基础文件上传</h2>
                <p class="section-desc">支持图片、音频、PDF等格式，单文件上传</p>
                <FileUpload v-model="basicFiles" :allowed-types="['image/*', 'audio/*', 'application/pdf']"
                    :max-size="5 * 1024 * 1024" @success="handleUploadSuccess" @error="handleUploadError"
                    @remove="handleFileRemove" />
            </div>

            <!-- 多文件上传 -->
            <div class="upload-section">
                <h2 class="section-title">多文件上传</h2>
                <p class="section-desc">支持同时上传多个文件，适合批量处理</p>
                <FileUpload v-model="multipleFiles" :multiple="true" :allowed-types="['image/*']"
                    :max-size="2 * 1024 * 1024" @success="handleUploadSuccess" @error="handleUploadError"
                    @remove="handleFileRemove" />
            </div>

            <!-- 文档上传 -->
            <div class="upload-section">
                <h2 class="section-title">文档上传</h2>
                <p class="section-desc">支持Word、PDF、Excel等常见文档格式</p>
                <FileUpload v-model="documentFiles" :allowed-types="[
                    'application/pdf',
                    'application/msword',
                    'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
                    'application/vnd.ms-excel',
                    'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
                ]" :max-size="20 * 1024 * 1024" @success="handleUploadSuccess" @error="handleUploadError"
                    @remove="handleFileRemove" />
            </div>

            <!-- 禁用状态 -->
            <div class="upload-section">
                <h2 class="section-title">禁用状态</h2>
                <p class="section-desc">上传组件禁用状态示例</p>
                <FileUpload v-model="disabledFiles" :disabled="true" :allowed-types="['image/*']"
                    :max-size="5 * 1024 * 1024" />
            </div>
        </div>

        <!-- 文件统计 -->
        <div class="file-stats">
            <h2 class="stats-title">文件统计</h2>
            <div class="stats-grid">
                <div class="stat-item">
                    <div class="stat-number">{{ totalFiles }}</div>
                    <div class="stat-label">总文件数</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">{{ totalSize }}</div>
                    <div class="stat-label">总大小</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">{{ successFiles }}</div>
                    <div class="stat-label">上传成功</div>
                </div>
                <div class="stat-item">
                    <div class="stat-number">{{ errorFiles }}</div>
                    <div class="stat-label">上传失败</div>
                </div>
            </div>
        </div>

        <!-- 操作按钮 -->
        <div class="action-buttons">
            <el-button type="primary" @click="clearAllFiles">清空所有文件</el-button>
            <el-button @click="exportFileList">导出文件列表</el-button>
            <el-button type="success" @click="downloadAllFiles">下载所有文件</el-button>
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage } from 'element-plus'
import FileUpload from '@/components/FileUpload.vue'
import type { UploadFile as ApiUploadFile } from '@/api/upload/models'

// 定义组件使用的文件类型（与FileUpload组件保持一致）
interface ComponentUploadFile {
    uid: string
    name: string
    size: number
    type: string
    status: 'pending' | 'uploading' | 'success' | 'error'
    percentage?: number
    url?: string
    response?: any
    raw?: File
}

// 文件列表
const basicFiles = ref<ComponentUploadFile[]>([])
const multipleFiles = ref<ComponentUploadFile[]>([])
const documentFiles = ref<ComponentUploadFile[]>([])
const disabledFiles = ref<ComponentUploadFile[]>([])

// 计算属性
const allFiles = computed(() => [
    ...basicFiles.value,
    ...multipleFiles.value,
    ...documentFiles.value,
    ...disabledFiles.value
])

const totalFiles = computed(() => allFiles.value.length)

const totalSize = computed(() => {
    const totalBytes = allFiles.value.reduce((sum, file) => sum + file.size, 0)
    return formatFileSize(totalBytes)
})

const successFiles = computed(() =>
    allFiles.value.filter(file => file.status === 'success').length
)

const errorFiles = computed(() =>
    allFiles.value.filter(file => file.status === 'error').length
)

// 文件大小格式化
const formatFileSize = (bytes: number) => {
    if (bytes === 0) return '0 B'
    const k = 1024
    const sizes = ['B', 'KB', 'MB', 'GB']
    const i = Math.floor(Math.log(bytes) / Math.log(k))
    return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 事件处理
const handleUploadSuccess = (file: ComponentUploadFile, response: any) => {
    ElMessage.success(`文件 ${file.name} 上传成功`)
}

const handleUploadError = (file: ComponentUploadFile, error: any) => {
    ElMessage.error(`文件 ${file.name} 上传失败: ${error.message}`)
}

const handleFileRemove = (file: ComponentUploadFile, index: number) => {
    ElMessage.info(`文件 ${file.name} 已移除`)
}

// 操作函数
const clearAllFiles = () => {
    basicFiles.value = []
    multipleFiles.value = []
    documentFiles.value = []
    disabledFiles.value = []
    ElMessage.success('所有文件已清空')
}

const exportFileList = () => {
    const fileList = allFiles.value.map(file => ({
        name: file.name,
        size: formatFileSize(file.size),
        type: file.type,
        status: file.status,
        url: file.url
    }))

    const dataStr = JSON.stringify(fileList, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    const url = URL.createObjectURL(dataBlob)

    const link = document.createElement('a')
    link.href = url
    link.download = `file-list-${Date.now()}.json`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('文件列表已导出')
}

const downloadAllFiles = () => {
    const successFiles = allFiles.value.filter(file => file.status === 'success' && file.url)

    if (successFiles.length === 0) {
        ElMessage.warning('没有可下载的文件')
        return
    }

    successFiles.forEach(file => {
        if (!file.url) return
        const link = document.createElement('a')
        link.href = file.url
        link.download = file.name
        document.body.appendChild(link)
        link.click()
        document.body.removeChild(link)
    })

    ElMessage.success(`已开始下载 ${successFiles.length} 个文件`)
}
</script>

<style scoped>
.file-upload-view {
    padding: 12px;
    /* margin: 0 auto; */
}

.page-header {
    text-align: center;
    margin-bottom: 32px;
}

.page-title {
    font-size: 28px;
    font-weight: bold;
    color: #333;
    margin: 0 0 8px 0;
}

.page-desc {
    font-size: 14px;
    color: #666;
    margin: 0;
}

.upload-sections {
    display: flex;
    flex-direction: row;
    gap: 16px;
    margin-bottom: 32px;
    flex-wrap: wrap;
}

.upload-section {
    background: #fff;
    border-radius: 8px;
    padding: 10px 8px 6px 8px;
    box-shadow: 0 1px 6px rgba(0, 0, 0, 0.05);
    border: 1px solid #e8e8e8;
    flex: 1 1 0;
    min-width: 0;
    max-width: 25%;
    display: flex;
    flex-direction: column;
    align-items: stretch;
}

.section-title {
    font-size: 14px;
    font-weight: 600;
    color: #333;
    margin: 0 0 2px 0;
}

.section-desc {
    font-size: 11px;
    color: #888;
    margin: 0 0 6px 0;
}

/* 文件列表紧凑样式 */
/* 已移除，因为FileUpload.vue组件现在有了自己的紧凑样式 */

/* 上传区域样式优化 */
:deep(.upload-area) {
    min-height: 70px !important;
    padding: 8px 6px !important;
    border-radius: 6px !important;
    border: 2px dashed #d9d9d9 !important;
    background: #fafafa !important;
    transition: all 0.3s ease !important;
}

:deep(.upload-area:hover) {
    border-color: #409eff !important;
    background: #f0f8ff !important;
}

:deep(.upload-area .upload-content) {
    padding: 8px 6px !important;
    gap: 6px !important;
}

:deep(.upload-area .upload-icon) {
    font-size: 24px !important;
    color: #999 !important;
    margin-bottom: 2px !important;
}

:deep(.upload-area .upload-title) {
    font-size: 12px !important;
    color: #666 !important;
    margin-bottom: 1px !important;
}

:deep(.upload-area .upload-desc) {
    font-size: 10px !important;
    color: #999 !important;
    margin-bottom: 1px !important;
}

:deep(.upload-area .upload-size) {
    font-size: 10px !important;
    color: #999 !important;
    margin-bottom: 4px !important;
}

:deep(.upload-area .el-button) {
    font-size: 11px !important;
    padding: 4px 8px !important;
    height: 24px !important;
    border-radius: 4px !important;
}

/* 禁用状态样式 */
:deep(.upload-area--disabled) {
    background: #f5f5f5 !important;
    border-color: #e8e8e8 !important;
    opacity: 0.6 !important;
}

:deep(.upload-area--disabled .upload-icon) {
    color: #ccc !important;
}

:deep(.upload-area--disabled .upload-title),
:deep(.upload-area--disabled .upload-desc),
:deep(.upload-area--disabled .upload-size) {
    color: #ccc !important;
}

:deep(.upload-area--disabled .el-button) {
    background: #f5f5f5 !important;
    border-color: #e8e8e8 !important;
    color: #ccc !important;
    cursor: not-allowed !important;
}

.file-stats {
    background: #fff;
    border-radius: 8px;
    padding: 20px;
    box-shadow: 0 1px 8px rgba(0, 0, 0, 0.06);
    border: 1px solid #e8e8e8;
    margin-bottom: 20px;
}

.stats-title {
    font-size: 16px;
    font-weight: 600;
    color: #333;
    margin: 0 0 16px 0;
}

.stats-grid {
    display: grid;
    grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
    gap: 16px;
}

.stat-item {
    text-align: center;
    padding: 16px;
    background: #f8f9fa;
    border-radius: 6px;
    border: 1px solid #e9ecef;
}

.stat-number {
    font-size: 24px;
    font-weight: bold;
    color: #667eea;
    margin-bottom: 6px;
}

.stat-label {
    font-size: 12px;
    color: #666;
}

.action-buttons {
    display: flex;
    gap: 10px;
    justify-content: center;
    flex-wrap: wrap;
}

/* 响应式设计 */
@media (max-width: 1200px) {
    .upload-section {
        max-width: 50%;
    }
}

@media (max-width: 900px) {
    .upload-section {
        max-width: 100%;
    }

    .upload-sections {
        flex-direction: column;
        gap: 12px;
    }
}

@media (max-width: 600px) {
    .file-upload-view {
        padding: 8px;
    }

    .upload-section {
        padding: 8px 6px;
    }
}
</style>
